<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1200px"
    custom-class="scrollable-dialog"
    :close-on-click-modal="false"
  >
    <el-form
      size="small"
      :model="storeForm"
      ref="storeForm"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库类别">
            <label> {{ storeForm.applyCategoryName }}</label>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否上传资质证书">
            <el-radio-group v-model="storeForm.isType" @change="typeChange">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="cumot-filex">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <template v-if="storeForm.isType == 1">
              <span>资质证书</span>
            </template>
            <template v-else>
              资质证书
            </template>
          </div>
          <div class="mut-box">
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="qualificationCertificateFileList"
              :on-remove="function(file, fileList) {return handleRemove(file,fileList,'qualificationCertificateFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file,fileList,'qualificationCertificateFileList')}">
              <el-button
                type="primary"
                :disabled="storeForm.isType == 2"
                size="mini"
                >选择上传</el-button
              >
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
            <template v-if="qualificationCertificateFileList.length">
              <div
                class="blocks-file"
                v-for="(item, index) in qualificationCertificateFileList"
                :key="index"
              >
                <label class="demonstration">{{ item.name }}</label>
                <div class="lbs">
                  <el-date-picker
                    v-model="item.time"
                    type="daterange"
                    style="width: 100%;"
                    range-separator="至"
                    value-format="yyyy-MM-DD"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                </div>
              </div>
            </template>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <template v-if="storeForm.isType == 2">
              <span>不上传资质证书理由</span>
            </template>
            <template v-else>
              不上传资质证书理由
            </template>
          </div>
          <div class="mut-box">
            <el-input
              type="textarea"
              :rows="5"
              :disabled="storeForm.isType == 1"
              v-model="storeForm.qualificationCertificateFileReason"
              placeholder="请输入不上传资质理由"
            ></el-input>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>业绩资料</span>
          </div>
          <div class="mut-box">
            <p style="margin-top: 0;line-height: 20px;">
              提供符合公告要求的业绩（金额、个数、类别、时间），并提供对应的转款凭证或发票；若是新项目暂未产生费用，请提供书面说明并盖章
            </p>
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="performanceFileList"
              :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'performanceFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file, fileList, 'performanceFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>财务报告（报表）</span>
          </div>
          <div class="mut-box">
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="financialReportFileList"
              :on-remove="function(file, fileList) {return handleRemove(file,fileList,'financialReportFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file,fileList,'financialReportFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>缴纳税收证明或完税证明</span>
            <el-button
              type="text"
              style="float: right; padding: 0"
              @click="getKeyResult('egimg1', '缴纳税收证明或完税证明示例图')"
              size="mini"
              >【查看示例图】</el-button
            >
          </div>
          <div class="mut-box">
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="taxFileList"
              :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'taxFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file, fileList, 'taxFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>缴纳社保证明</span>
            <el-button
              type="text"
              style="float: right; padding: 0"
              @click="getKeyResult('egimg2', '缴纳社保证明示例图')"
              size="mini"
              >【查看示例图】</el-button
            >
          </div>
          <div class="mut-box">
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="socialSecurityFileList"
              :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'socialSecurityFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file, fileList, 'socialSecurityFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>良好的商业信誉</span>
            <el-button
              type="text"
              style="float: right; padding: 0"
              @click="getKeyResult('egimg3', '商业信誉示例图')"
              size="mini"
              >【查看示例图】</el-button
            >
          </div>
          <div class="mut-box">
            <p style="margin-top: 0;line-height: 20px;">
              ①提供“信用中国
              <a
                style="color: rgb(64, 158, 255);"
                href="https://www.creditchina.gov.cn/"
                target="_blank"
                >https://www.creditchina.gov.cn/</a
              >
              网站相关截图证明；
            </p>
            <p style="margin-top: 0;line-height: 20px;">
              ②提供“国家企业信用公示系统
              <a
                href="https://www.gsxt.gov.cn/"
                style="color: rgb(64, 158, 255);"
                target="_blank"
                >https://www.gsxt.gov.cn/</a
              >
              网站相关截图证明;
            </p>
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="businessCreditFileList"
              :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'businessCreditFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file, fileList, 'businessCreditFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            其他
          </div>
          <div class="mut-box">
            <div style="margin-bottom: 10px;">
              <el-input
                type="textarea"
                :rows="5"
                maxlength="300"
                show-word-limit
                v-model="storeForm.otherRemarks"
                placeholder="备注信息，限制300个文字"
              ></el-input>
            </div>
            <el-upload
              accept="image/*,application/pdf"
              list-type="picture"
              :on-preview="handlePreview"
              :file-list="otherFileList"
              :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'otherFileList')}"
              :before-upload="beforeAvatarUpload"
              action="#"
              :http-request="function(file, fileList) {return handleChange(file, fileList, 'otherFileList')}">
              <el-button type="primary" size="mini">选择上传</el-button>
              <div slot="tip" class="cumost-upload-tip">
                支持图片和pdf
              </div>
            </el-upload>
          </div>
        </el-card>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="visible = false">取 消</el-button>
      <el-button size="small" :loading="loading" type="primary" @click="submitAddly()"
        >提交</el-button
      >
    </div>

    <el-dialog title="图片预览" append-to-body :visible.sync="innerVisible">
      <img :src="previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="innerVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :title="tips.title"
      append-to-body
      width="600px"
      :visible.sync="tips.visible"
    >
      <div v-if="tips.type == 1" class="shili-box">
        <div v-if="ruleForm.egimg1">
          <label>{{ ruleForm.egimg1 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg1FileList" :key="item.url" />
        <el-empty
          v-if="!ruleForm.egimg1 && egimg1FileList.length == 0"
          description="暂无示例信息"
        ></el-empty>
      </div>
      <div v-if="tips.type == 2" class="shili-box">
        <div v-if="ruleForm.egimg2">
          <label>{{ ruleForm.egimg2 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg2FileList" :key="item.url" />
        <el-empty
          v-if="!ruleForm.egimg2 && egimg2FileList.length == 0"
          description="暂无示例信息"
        ></el-empty>
      </div>
      <div v-if="tips.type == 3" class="shili-box">
        <div v-if="ruleForm.egimg3">
          <label>{{ ruleForm.egimg3 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg3FileList" :key="item.url" />
        <el-empty
          v-if="!ruleForm.egimg3 && egimg3FileList.length == 0"
          description="暂无示例信息"
        ></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tips.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierStoreInfo, supplierStoreUpdate } from "@/api/supplier_api";
import { getDetailByKey } from "@/api/about_api";
import pdfimg from "@/assets/pdf_file.png";
export default {
  props: {
    title: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  data() {
    return {
      visible: false,
      innerVisible: false,
      previewUrl: "",
      treeData: [],
      storeForm: {
        supplierStoreIds: "",
        applyCategoryName: "",
        isType: 1,
        applyId: "",
        otherRemarks:"",
        qualificationCertificateFileReason: ""
      },
      qualificationCertificateFileList: [],
      performanceFileList: [],
      financialReportFileList: [],
      taxFileList: [],
      socialSecurityFileList: [],
      businessCreditFileList: [],
      otherFileList: [],
      storeType: "", //入库1资料2
      //示例
      tips: {
        visible: false,
        type: 1,
        title: ""
      },
      ruleForm: {
        egimg1: "",
        egimg2: "",
        egimg3: ""
      },
      loading:false,
      egimg1FileList: [],
      egimg2FileList: [],
      egimg3FileList: []
    };
  },
  mounted() {},
  methods: {
    ...mapActions({
      uploadFile: "user/uploadFile"
    }),
    openStoreForm(row) {
      console.log(row)
      this.storeForm.supplierStoreIds = row.applyCategoryId;
      const arrayRegex = /^\[.*\]$/;
      if (arrayRegex.test(row.applyCategoryName)) {
        let str = JSON.parse(row.applyCategoryName);
        this.storeForm.applyCategoryName = str[0];
      } else {
        this.storeForm.applyCategoryName = row.applyCategoryName;
      }
      this.storeForm.applyId = row.applyId;
      //入库和资料修改和驳回 都走这里    但现在不能确定驳回和修改资料的状态
      if (row.storeStatus == "1") {
        this.storeType = "2";
      } else if (row.storeStatus == "2") {
        this.storeType = "1";
      }
      this.getStoreInfo(row);
      this.visible = true;
    },
    async getStoreInfo(row) {
      //清空资质证书和理由数据
      this.qualificationCertificateFileList = [];
      this.storeForm.qualificationCertificateFileReaso = "";
      const { code, data } = await getSupplierStoreInfo({ id: row.id });
      if (code == 200) {
        if (data) {
          if (data.qualificationCertificateFile) {
            this.qualificationCertificateFileList = JSON.parse(
              data.qualificationCertificateFile
            );
            this.storeForm.isType = 1;
          }
          if (data.qualificationCertificateFileReason) {
            this.storeForm.qualificationCertificateFileReason =
              data.qualificationCertificateFileReason;
            this.storeForm.isType = 2;
          }
          if (data.performanceFile) {
            this.performanceFileList = JSON.parse(data.performanceFile);
          }
          if (data.financialReportFile) {
            this.financialReportFileList = JSON.parse(data.financialReportFile);
          }
          if (data.taxProofFile) {
            this.taxFileList = JSON.parse(data.taxProofFile);
          }
          if (data.socialSecurityFile) {
            this.socialSecurityFileList = JSON.parse(data.socialSecurityFile);
          }
          if (data.businessCreditFile) {
            this.businessCreditFileList = JSON.parse(data.businessCreditFile);
          }
          if (data.otherFile) {
            this.otherFileList = JSON.parse(data.otherFile);
          }
          if (data.otherRemarks) {
            this.storeForm.otherRemarks = data.otherRemarks
          }
        }
      }
    },
    async getKeyResult(dataKey, dataTitle) {
      this.egimg1FileList = [];
      this.egimg2FileList = [];
      this.egimg3FileList = [];
      let { code, data } = await getDetailByKey(dataKey);
      if (code === 200) {
        this.tips.visible = true;
        this.tips.title = dataTitle;
        const regex = /#~#/;
        if (data && "egimg1" == data.key) {
          this.tips.type = 1;
          if (data.value) {
            if (regex.test(data.value)) {
              const parts = data.value.split("#~#");
              this.ruleForm.egimg1 = parts[0];
              this.egimg1FileList = JSON.parse(parts[1]);
            } else {
              this.egimg1FileList = JSON.parse(data.value);
            }
          }
        }
        if (data && "egimg2" == data.key) {
          this.tips.type = 2;
          if (data.value) {
            if (regex.test(data.value)) {
              const parts = data.value.split("#~#");
              this.ruleForm.egimg2 = parts[0];
              this.egimg2FileList = JSON.parse(parts[1]);
            } else {
              this.egimg2FileList = JSON.parse(data.value);
            }
          }
        }
        if (data && "egimg3" == data.key) {
          this.tips.type = 3;
          if (data.value) {
            if (regex.test(data.value)) {
              const parts = data.value.split("#~#");
              this.ruleForm.egimg3 = parts[0];
              this.egimg3FileList = JSON.parse(parts[1]);
            } else {
              this.egimg3FileList = JSON.parse(data.value);
            }
          }
        }
      }
    },
    handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls);
      } else {
        this.previewUrl = file.url;
        this.innerVisible = true;
      }
    },
    handleRemove(file, fileList, fliedKey) {
      const index = this[fliedKey].indexOf(file);
      if (index > -1) {
        this[fliedKey].splice(index, 1);
      }
    },
    async handleChange(file, fileList, fileKey) {
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        if (file.file.type == "application/pdf") {
          this[fileKey].push({
            name: file.file.name,
            time:[],
            url: pdfimg,
            urls: url,
            type: 1
          });
        } else {
          this[fileKey].push({ name: file.file.name, url: url, type: 2,time:[] });
        }
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf";
      if (!isJPG) {
        this.$message.error("附件只能是 jpeg，png，jpg 格式或pdf格式!");
      }
      return isJPG;
    },
    typeChange(e) {
      if (e == 1) {
        this.storeForm.qualificationCertificateFileReason = "";
      } else {
        this.qualificationCertificateFileList = [];
      }
    },
    async submitAddly() {
      let that = this;
      let param = {};
      param.isUploadQualificationCertificateFile = this.storeForm.isType;
      if (this.storeForm.isType == 1) {
        if (this.qualificationCertificateFileList.length == 0) {
          this.$message.error("请上传资质证书");
          return;
        }

         for (let i = 0; i < this.qualificationCertificateFileList.length; i++){
            let vals = this.qualificationCertificateFileList[i]
            if (vals.time.length == 0) {
              let txt = '资质证书（附件名称）' + vals.name + '未填写开始结束日期！'
              this.$message.error(txt);
              return;
            }
          }

        param.qualificationCertificateFile = JSON.stringify(
          this.qualificationCertificateFileList
        );
        param.qualificationCertificateFileReason = "";
      } else {
        if (!this.storeForm.qualificationCertificateFileReason) {
          this.$message.error("请填写不上传资质证书理由");
          return;
        }
        param.qualificationCertificateFileReason = this.storeForm.qualificationCertificateFileReason;
        param.qualificationCertificateFile = "";
      }
      if (this.performanceFileList.length == 0) {
        this.$message.error("请上传业绩资料");
        return;
      }
      param.performanceFile = JSON.stringify(this.performanceFileList);
      if (this.financialReportFileList.length == 0) {
        this.$message.error("请上传财务报告");
        return;
      }
      param.financialReportFile = JSON.stringify(this.financialReportFileList);
      if (this.taxFileList.length == 0) {
        this.$message.error("请上传缴纳税收证明或完税证明");
        return;
      }
      param.taxProofFile = JSON.stringify(this.taxFileList);
      if (this.socialSecurityFileList.length == 0) {
        this.$message.error("请上传缴纳社保证明");
        return;
      }
      param.socialSecurityFile = JSON.stringify(this.socialSecurityFileList);
      if (this.businessCreditFileList.length == 0) {
        this.$message.error("请上传商业信誉");
        return;
      }
      param.businessCreditFile = JSON.stringify(this.businessCreditFileList);

      param.otherFile = "";
      if (this.otherFileList.length >= 1) {
        param.otherFile = JSON.stringify(this.otherFileList);
      }

      if (this.storeForm.otherRemarks) {
        param.otherRemarks = this.storeForm.otherRemarks
      }

      param.storeType = "2"; //this.storeType
      param.supplierStoreIds = this.storeForm.supplierStoreIds;
      param.supplierStoreName = this.storeForm.applyCategoryName;
      param.applyId = this.storeForm.applyId;
      this.loading = true
      try {
        const { code } = await supplierStoreUpdate(param);
        if (code == 200) {
          let txt =
            "入库类别" +
            this.storeForm.applyCategoryName +
            "更新资料提交成功，审核结果通过短信发送到手机！";
          this.$alert(txt, "温馨提示", {
            confirmButtonText: "关闭",
            type: "success",
            callback: action => {
              that.clearData();
              that.$emit("onOk", true);
              that.visible = false;
            }
          }).catch(() => {
            that.clearData();
            that.$emit("onOk", true);
            that.visible = false;
          });
        }
      } finally {
        this.loading = false
      }
    },
    clearData() {
      (this.storeForm = {
        supplierStoreIds: "",
        isType: 1,
        qualificationCertificateFileReason: ""
      }),
        (this.qualificationCertificateFileList = []);
      this.performanceFileList = [];
      this.financialReportFileList = [];
      this.taxFileList = [];
      this.socialSecurityFileList = [];
      this.businessCreditFileList = [];
      this.otherFileList = [];
    }
  }
};
</script>
<style scoped>
.cumost-upload-tip {
  font-size: 12px;
  color: #606266;
  display: inline-block;
  margin-left: 20px;
}
.shili-box label {
  text-align: center;
  padding: 10px;
  font-size: 20px;
  display: block;
  color: #000;
}
.shili-box img {
  display: block;
  margin: 10px auto;
  max-width: 100%;
}
.mut-box {
  min-height: 140px;
}
.cumot-filex {
  display: flex;
  grid-column-gap: 2%;
  flex-wrap: wrap;
}
.box-card {
  flex: 0 0 49%;
}
.box-card span:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.blocks-file {
  display: flex;
  flex-direction: column;
  margin-top: 15px;
}
.demonstration {
  word-break: break-word;
  margin-bottom: 4px;
}
.lbs {
  flex: 1;
}
</style>
